package qinius

import (
	"context"

	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
)

const (
	Exist    = "file exists"
	defUrl   = "https://qnc.qjnice.com/" //地址
	defSpace = "qjpublic"                //空间
)

type Qiniu struct {
	Key    string //key
	Secret string //secret
	Url    string //前缀
	Space  string //空间
	err    error  //错误
}

// NewQiniu 新建七牛
//@key ,key
//@secret ,secret
//@url ,url,例如"http://qnc.qjnice.com/"
//@space ,储存空间,例如 "qjpublic"
func NewQiniu(key, secret, url, space string) *Qiniu {
	return &Qiniu{
		Key:    key,
		Secret: secret,
		Url:    url,
		Space:  space,
	}
}

func DefQiniu() *Qiniu {
	return &Qiniu{
		Key:    defKey,
		Secret: defSecret,
		Url:    defUrl,
		Space:  defSpace,
	}
}

//设置七牛空间地址
func (this *Qiniu) SetSpace(space string) *Qiniu {
	this.Space = space
	return this
}

//
func (this *Qiniu) New(key, secret string) *Qiniu {
	this.Key = key
	this.Secret = secret
	return this
}

//默认"https://qnc.qjnice.com/"
func (this *Qiniu) SetUrl(url string) *Qiniu {
	this.Url = url
	return this
}

func (this *Qiniu) SetErr(err error) *Qiniu {
	this.err = err
	return this
}

// Upload 上传七牛私有方法
//@fileName,文件名称
//@filePath,文件夹路径
func (this *Qiniu) Upload(filePath, fileName string) (string, error) {
	if this.err != nil {
		return "", this.err
	}
	return this.upload(filePath, fileName)
}

// upload 上传七牛私有方法
//@fileName,文件名称
//@filePath,文件夹路径
func (this *Qiniu) upload(fillPath, fileName string) (string, error) {
	mac := qbox.NewMac(this.Key, this.Secret)
	putPolicy := storage.PutPolicy{Scope: this.Space}
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuadong, // 空间对应的机房
		UseHTTPS:      false,                // 是否使用https域名
		UseCdnDomains: false,                // 上传是否使用CDN上传加速
	}
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	err := formUploader.PutFile(context.Background(), &ret, upToken, fileName, this.fullPath(fillPath, fileName), nil)
	return this.Url + ret.Key, err
}

func (this *Qiniu) fullPath(fillPath, fileName string) string {
	if len(fileName) != 0 && len(fillPath) != 0 && fillPath[len(fillPath)-1] == '/' && fileName[0] == '/' {
		return fillPath[:len(fillPath)-1] + fileName
	}
	return fillPath + fileName
}
